# -*- coding:utf-8 -*-
import re
import time
try:
    import cookielib
except:
    import http.cookiejar as cookielib
from PIL import Image

import requests

session = requests.session()
session.cookies = cookielib.LWPCookieJar(filename='cookies.txt')
try:
    session.cookies.load(ignore_discard=True)
except:
    print "cookie 未能加载"

agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36"


header = {
    "User-Agent": agent
}


def get_xsrf():
    response = requests.get("https://www.zhihu.com", headers=header)
    xsrf_value = re.match(r'.*name="_xsrf" value="(.*?)"', response.text, re.DOTALL)
    if xsrf_value:
        return xsrf_value.group(1)
    else:
        return ""


def zhihu_login(account, password):
    if re.match("^1\d{10}", account):
        print "手机号码登录"
        post_url = "https://www.zhihu.com/login/phone_num"
        post_data = {
            "_xsrf": get_xsrf(),
            "password": password,
            "phone_num": account,
            # "captcha_type": "en"  # 验证码
        }
        # get check code image
        checkcode_url = "https://www.zhihu.com/captcha.gif?r=" + str(int(time.time()*1000)) + "&type=login&lang=en"

        resp = session.get(checkcode_url, headers=header).content
        with open("checkcode.gif", "wb") as f:
            f.write(resp)
        f.close()

        try:
            im = Image.open("checkcode.gif")
            im.show()
            im.close()
        except:
            pass

        post_data["captcha"] = raw_input("checkcode:")
        response_text = session.post(post_url, data=post_data, headers=header)
        session.cookies.save()


def is_login():
    inbox_url = "https://www.zhihu.com/inbox"
    response = session.get(inbox_url, headers=header,allow_redirects=False)
    print response.text

    if response.status_code != 200:
        return False
    else:
        return True

is_login()